package org.cloud.scheduler.controller;

import java.util.List;
import java.util.Map;

import org.cloud.common.model.R;
import org.cloud.common.util.ValidatorUtils;
import org.cloud.module.common.entity.ScheduleJobEntity;
import org.cloud.module.common.util.PageUtils;
import org.cloud.scheduler.service.ScheduleJobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 定时任务控制器
 * @author wangyuan
 * @since 2019年6月15日 下午10:51:23
 *
 */
@RestController
@RequestMapping("/job")
public class ScheduleJobController {
	
	@Autowired
	private ScheduleJobService scheduleJobService;
	
	/**
	 * 定时任务列表
	 */
	@RequestMapping("/list")
	public R list(@RequestParam Map<String, Object> params){
		PageUtils page = scheduleJobService.queryPage(params);

		return R.ok().put("page", page);
	}
	
	/**
	 * 定时任务信息
	 */
	@RequestMapping("/info/{jobId}")
	public R info(@PathVariable("jobId") Long jobId){
		ScheduleJobEntity schedule = scheduleJobService.getById(jobId);
		
		return R.ok().put("schedule", schedule);
	}
	
	/**
	 * 保存定时任务
	 */
	@RequestMapping("/save")
	public R save(@ModelAttribute ScheduleJobEntity scheduleJob){
		ValidatorUtils.validateEntity(scheduleJob);
		
		scheduleJobService.saveJob(scheduleJob);
		
		return R.ok();
	}
	
	/**
	 * 修改定时任务
	 */
	@RequestMapping("/update")
	public R update(@ModelAttribute ScheduleJobEntity scheduleJob){
		ValidatorUtils.validateEntity(scheduleJob);
		
		ScheduleJobEntity job = scheduleJobService.getById(scheduleJob.getId());
		job.setBeanName(scheduleJob.getBeanName());
		job.setJobParams(scheduleJob.getJobParams());
		job.setCronExpression(scheduleJob.getCronExpression());
		job.setRemark(scheduleJob.getRemark());
				
		scheduleJobService.update(job);
		
		return R.ok();
	}
	
	/**
	 * 删除定时任务
	 */
	@RequestMapping("/delete")
	public R delete(@RequestParam List<Long> jobIds){
		scheduleJobService.deleteBatch(jobIds);
		
		return R.ok();
	}
	
	/**
	 * 立即执行任务
	 */
	@RequestMapping("/run")
	public R run(@RequestParam List<Long> jobIds){
		scheduleJobService.doRun(jobIds);
		
		return R.ok();
	}
	
	/**
	 * 暂停定时任务
	 */
	@RequestMapping("/pause")
	public R pause(@RequestParam List<Long> jobIds){
		scheduleJobService.doPause(jobIds);
		
		return R.ok();
	}
	
	/**
	 * 恢复定时任务
	 */
	@RequestMapping("/resume")
	public R resume(@RequestParam List<Long> jobIds){
		scheduleJobService.doResume(jobIds);
		
		return R.ok();
	}

}
